{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Helpdesk Medium"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading spark-stubs, spark-hive\n",
      "Adding Hive conf dir /opt/hive/conf to classpath\n",
      "Creating SparkSession\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "SLF4J: No SLF4J providers were found.\n",
      "SLF4J: Defaulting to no-operation (NOP) logger implementation\n",
      "SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<a target=\"_blank\" href=\"http://jupyter:4040\">Spark UI</a>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36m$ivy.$                                  \n",
       "\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.log4j.{Level, Logger}\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.types._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.functions._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.expressions.Window\n",
       "\n",
       "\u001b[39m\n",
       "\u001b[36mspark\u001b[39m: \u001b[32mSparkSession\u001b[39m = org.apache.spark.sql.SparkSession@7f1f77e9"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import $ivy.`org.apache.spark::spark-sql:3.4.0`\n",
    "\n",
    "import org.apache.log4j.{Level, Logger}\n",
    "Logger.getLogger(\"org\").setLevel(Level.OFF)\n",
    "\n",
    "import org.apache.spark._\n",
    "import org.apache.spark.sql._\n",
    "import org.apache.spark.sql.types._\n",
    "import org.apache.spark.sql.functions._\n",
    "import org.apache.spark.sql.expressions.Window\n",
    "\n",
    "val spark = {\n",
    "    NotebookSparkSession.builder()\n",
    "    .progress(false)\n",
    "    .appName(\"app12-2\")\n",
    "    // .master(\"spark://192.168.31.31:7077\")\n",
    "    .master(\"local[*]\")\n",
    "    .config(\"spark.sql.warehouse.dir\", \n",
    "            \"hdfs://192.168.31.31:9000/user/hive/warehouse\") \n",
    "    .config(\"spark.cores.max\", \"4\") \n",
    "    .config(\"spark.executor.instances\", \"1\") \n",
    "    .config(\"spark.executor.cores\", \"2\") \n",
    "    .config(\"spark.executor.memory\", \"10g\") \n",
    "    .config(\"spark.shuffle.service.enabled\", \"false\") \n",
    "    .config(\"spark.dynamicAllocation.enabled\", \"false\") \n",
    "    .config(\"spark.sql.catalogImplementation\", \"hive\")\n",
    "    .config(\"spark.sql.repl.eagerEval.enabled\", \"true\")\n",
    "    .config(\"spark.driver.allowMultipleContexts\", \"true\")\n",
    "    .getOrCreate()\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36mspark.implicits._\n",
       "\u001b[39m\n",
       "defined \u001b[32mfunction\u001b[39m \u001b[36msc\u001b[39m\n",
       "\u001b[36mhiveCxt\u001b[39m: \u001b[32msql\u001b[39m.\u001b[32mhive\u001b[39m.\u001b[32mHiveContext\u001b[39m = org.apache.spark.sql.hive.HiveContext@434083ee"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import spark.implicits._\n",
    "def sc = spark.sparkContext\n",
    "val hiveCxt = new org.apache.spark.sql.hive.HiveContext(sc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mRichDF\u001b[39m"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// Credit to Aivean\n",
    "implicit class RichDF(val ds:DataFrame) {\n",
    "    def showHTML(limit: Int = 50, truncate: Int = 100) = {\n",
    "        import xml.Utility.escape\n",
    "        val data = ds.take(limit)\n",
    "        val header = ds.schema.fieldNames.toSeq        \n",
    "        val rows: Seq[Seq[String]] = data.map { row =>\n",
    "          row.toSeq.map {cell =>\n",
    "            val str = cell match {\n",
    "              case null => \"null\"\n",
    "              case binary: Array[Byte] => binary.map(\"%02X\".format(_)).mkString(\"[\", \" \", \"]\")\n",
    "              case array: Array[_] => array.mkString(\"[\", \", \", \"]\")\n",
    "              case seq: Seq[_] => seq.mkString(\"[\", \", \", \"]\")\n",
    "              case _ => cell.toString\n",
    "            }\n",
    "            if (truncate > 0 && str.length > truncate) {\n",
    "              // do not show ellipses for strings shorter than 4 characters.\n",
    "              if (truncate < 4) str.substring(0, truncate)\n",
    "              else str.substring(0, truncate - 3) + \"...\"\n",
    "            } else {\n",
    "              str\n",
    "            }\n",
    "          }: Seq[String]\n",
    "        }\n",
    "    publish.html(s\"\"\" <table>\n",
    "                <tr>\n",
    "                 ${header.map(h => s\"<th>${escape(h)}</th>\").mkString}\n",
    "                </tr>\n",
    "                ${rows.map {row =>\n",
    "                  s\"<tr>${row.map{c => s\"<td>${escape(c)}</td>\" }.mkString}</tr>\"\n",
    "                }.mkString}\n",
    "            </table>\n",
    "        \"\"\")\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[36mshift\u001b[39m: \u001b[32mDataFrame\u001b[39m = [shift_date: string, shift_type: string ... 4 more fields]\n",
       "\u001b[36mstaff\u001b[39m: \u001b[32mDataFrame\u001b[39m = [staff_code: string, first_name: string ... 2 more fields]\n",
       "\u001b[36missue\u001b[39m: \u001b[32mDataFrame\u001b[39m = [call_date: string, call_ref: int ... 5 more fields]\n",
       "\u001b[36mshift_type\u001b[39m: \u001b[32mDataFrame\u001b[39m = [shift_type: string, start_time: string ... 1 more field]\n",
       "\u001b[36mlevel\u001b[39m: \u001b[32mDataFrame\u001b[39m = [level_code: int, manager: string ... 2 more fields]\n",
       "\u001b[36mcustomer\u001b[39m: \u001b[32mDataFrame\u001b[39m = [company_ref: int, company_name: string ... 6 more fields]\n",
       "\u001b[36mcaller\u001b[39m: \u001b[32mDataFrame\u001b[39m = [caller_id: int, company_ref: int ... 2 more fields]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "val shift = hiveCxt.table(\"sqlzoo.Shift\")\n",
    "val staff = hiveCxt.table(\"sqlzoo.Staff\")\n",
    "val issue = hiveCxt.table(\"sqlzoo.Issue\")\n",
    "val shift_type = hiveCxt.table(\"sqlzoo.Shift_type\")\n",
    "val level = hiveCxt.table(\"sqlzoo.Level\")\n",
    "val customer = hiveCxt.table(\"sqlzoo.Customer\")\n",
    "val caller = hiveCxt.table(\"sqlzoo.Caller\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.\n",
    "List the Company name and the number of calls for those companies with more than 18 calls.\n",
    "\n",
    "```\n",
    "+------------------+----+\n",
    "| Company_name     | cc |\n",
    "+------------------+----+\n",
    "| Gimmick Inc.     | 22 |\n",
    "| Hamming Services | 19 |\n",
    "| High and Co.     | 20 |\n",
    "+------------------+----+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>Company_name</th><th>cc</th>\n",
       "                </tr>\n",
       "                <tr><td>Hamming Services</td><td>19</td></tr><tr><td>Gimmick Inc.</td><td>22</td></tr><tr><td>High and Co.</td><td>20</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(issue.join(caller, \"Caller_id\")\n",
    " .join(customer, \"Company_ref\")\n",
    " .groupBy(\"Company_name\")\n",
    " .agg(count(\"Call_ref\").alias(\"cc\"))\n",
    " .filter(col(\"cc\")>18)\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7.\n",
    "Find the callers who have never made a call. Show first name and last name\n",
    "\n",
    "```\n",
    "+------------+-----------+\n",
    "| first_name | last_name |\n",
    "+------------+-----------+\n",
    "| David      | Jackson   |\n",
    "| Ethan      | Phillips  |\n",
    "+------------+-----------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>First_name</th><th>Last_name</th>\n",
       "                </tr>\n",
       "                <tr><td>David</td><td>Jackson</td></tr><tr><td>Ethan</td><td>Phillips</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(caller.join(issue, \"Caller_id\", joinType=\"left_anti\")\n",
    " .select(\"First_name\", \"Last_name\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8.\n",
    "For each customer show: Company name, contact name, number of calls where the number of calls is fewer than 5\n",
    "\n",
    "```\n",
    "+--------------------+------------+-----------+----+\n",
    "| Company_name       | first_name | last_name | nc |\n",
    "+--------------------+------------+-----------+----+\n",
    "| Pitiable Shipping  | Ethan      | McConnell |  4 |\n",
    "| Rajab Group        | Emily      | Cooper    |  4 |\n",
    "| Somebody Logistics | Ethan      | Phillips  |  2 |\n",
    "+--------------------+------------+-----------+----+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>Company_name</th><th>First_name</th><th>Last_name</th><th>nc</th>\n",
       "                </tr>\n",
       "                <tr><td>Pitiable Shipping</td><td>Ethan</td><td>McConnell</td><td>4</td></tr><tr><td>Somebody Logistics</td><td>Ethan</td><td>Phillips</td><td>2</td></tr><tr><td>Rajab Group</td><td>Emily</td><td>Cooper</td><td>4</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(issue.join(caller.select(\"Caller_id\", \"Company_ref\"), \"Caller_id\")\n",
    " .join(customer, \"Company_ref\")\n",
    " .groupBy(\"Company_ref\", \"Company_name\", \"Contact_id\")\n",
    " .agg(count(\"Call_ref\").alias(\"nc\"))\n",
    " .filter(col(\"nc\") < 5)\n",
    " .join(caller, (col(\"Contact_id\")===col(\"Caller_id\")))\n",
    " .select(\"Company_name\", \"First_name\", \"Last_name\", \"nc\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9.\n",
    "For each shift show the number of staff assigned. Beware that some roles may be NULL and that the same person might have been assigned to multiple roles (The roles are 'Manager', 'Operator', 'Engineer1', 'Engineer2').\n",
    "\n",
    "```\n",
    "+------------+------------+----+\n",
    "| Shift_date | Shift_type | cw |\n",
    "+------------+------------+----+\n",
    "| 2017-08-12 | Early      |  4 |\n",
    "| 2017-08-12 | Late       |  4 |\n",
    "| 2017-08-13 | Early      |  3 |\n",
    "| 2017-08-13 | Late       |  2 |\n",
    "| 2017-08-14 | Early      |  4 |\n",
    "| 2017-08-14 | Late       |  4 |\n",
    "| 2017-08-15 | Early      |  4 |\n",
    "| 2017-08-15 | Late       |  4 |\n",
    "| 2017-08-16 | Early      |  4 |\n",
    "| 2017-08-16 | Late       |  4 |\n",
    "+------------+------------+----+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>Shift_date</th><th>Shift_type</th><th>cw</th>\n",
       "                </tr>\n",
       "                <tr><td>2017-08-12</td><td>Early</td><td>4</td></tr><tr><td>2017-08-12</td><td>Late</td><td>4</td></tr><tr><td>2017-08-13</td><td>Early</td><td>3</td></tr><tr><td>2017-08-13</td><td>Late</td><td>2</td></tr><tr><td>2017-08-14</td><td>Early</td><td>4</td></tr><tr><td>2017-08-14</td><td>Late</td><td>4</td></tr><tr><td>2017-08-15</td><td>Early</td><td>4</td></tr><tr><td>2017-08-15</td><td>Late</td><td>4</td></tr><tr><td>2017-08-16</td><td>Early</td><td>4</td></tr><tr><td>2017-08-16</td><td>Late</td><td>4</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(shift.selectExpr(\n",
    "    \"Shift_date\", \"Shift_type\", \n",
    "    \"stack(4, 'Manager', Manager, 'Operator', Operator, \" + \n",
    "    \"'Engineer1', Engineer1, 'Engineer2', Engineer2) as (role, p)\")\n",
    " .dropDuplicates(\"Shift_date\", \"Shift_type\", \"p\")\n",
    " .na.drop()\n",
    " .groupBy(\"Shift_date\", \"Shift_type\")\n",
    " .agg(count(\"role\").alias(\"cw\"))\n",
    " .orderBy(\"Shift_date\", \"Shift_type\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10.\n",
    "Caller 'Harry' claims that the operator who took his most recent call was abusive and insulting. Find out who took the call (full name) and when.\n",
    "\n",
    "```\n",
    "+------------+-----------+---------------------+\n",
    "| first_name | last_name | call_date           |\n",
    "+------------+-----------+---------------------+\n",
    "| Emily      | Best      | 2017-08-16 10:25:00 |\n",
    "+------------+-----------+---------------------+\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>First_name</th><th>Last_name</th><th>Call_date</th>\n",
       "                </tr>\n",
       "                <tr><td>Emily</td><td>Best</td><td>2017-08-16 10:25:00.0</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(caller.filter(col(\"First_name\")===\"Harry\")\n",
    " .select(\"Caller_id\")\n",
    " .join(issue, \"Caller_id\")\n",
    " .join(staff, (issue(\"Taken_by\")===staff(\"Staff_code\")))\n",
    " .orderBy(col(\"Call_date\").desc)\n",
    " .select(\"First_name\", \"Last_name\", \"Call_date\")\n",
    " .limit(1)\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "spark.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.12.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
